package com.itheima.security.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/19 19:33
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    //远程注入
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByusername(username);
        if (user == null) {
            return null;
        }
        //如果user不为空,获取user的密码
        String password = user.getPassword();
        //获取该user的所有的角色放入集合中
        Set<Role> roles = user.getRoles();
        List<GrantedAuthority> list = new ArrayList<>();
        for (Role role : roles) {
            String keyword = role.getKeyword();
            list.add(new SimpleGrantedAuthority(keyword));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                String keyword1 = permission.getKeyword();
                list.add(new SimpleGrantedAuthority(keyword1));
            }
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, password, list);

        return userDetails;
    }
}
